package com.toyota.toyotaownerspoc.nearby;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.toyota.toyotaownerspoc.R;
import com.toyota.toyotaownerspoc.main.GpsLocaton;
import com.toyota.toyotaownerspoc.main.toyotaOwnersGlobal;

/*
 * HP06 Ability to Navigate to the Nearby Section: On tap of
the Nearby option on the homepage, the user will be redirected
to the Nearby section with the Dealer Listings page displayed by
default.
 */

public class Nearby extends Activity {

	 @SuppressLint("NewApi")
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        
	        //if location services are allowed 
			SharedPreferences preferences = getSharedPreferences(
					toyotaOwnersGlobal.PREFERENCES_FILE, MODE_PRIVATE);
			
			boolean locationServicesFlag = preferences.getBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES,false);
			
//			if (locationServicesFlag)
//			{
				
		        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		        	double latitude = 0.0;
		        	double longitude = 0.0;
		        	try{
			        	LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
			         	GpsLocaton locationListener = new GpsLocaton(locationManager);
			         	locationListener.updateLocation();
			         	latitude = locationListener.getLatitude();
			         	longitude = locationListener.getLongitude();
		        	
		         	// Show the Up button in the action bar.
		            getActionBar().setDisplayHomeAsUpEnabled(true);
		            
		            // Create the text view
		            TextView textView = new TextView(this); 
		            textView.setTextSize(40);
		            textView.setText("dfa");
		            
		            setContentView(R.layout.activity_nearby);
		           new GetZipIO(longitude, latitude).execute();
	        	}
	        	catch(Exception e){
	        		e.printStackTrace();
	        		Log.d("Nearby", e.getMessage());
	        	}
		      }
//			} else {
//				AlertDialog.Builder builder = new AlertDialog.Builder(findViewById(R.id.show_message).getContext());
//				//set alert message
//				builder.setMessage(R.string.location_permission_popup_text);
//			}
	    }
	    

	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case android.R.id.home:
	            NavUtils.navigateUpFromSameTask(this);
	            return true;
	        }
	        return super.onOptionsItemSelected(item);
	    }

		
		private class GetZipIO extends AsyncTask <Void, Void, String> {
			private double longitude;
			private double latitude;
			 public GetZipIO(double longitude, double latitude) {
			        super();
			        this.longitude = longitude;
			        this.latitude = latitude;

			        // do stuff
			    }
			protected String getContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {

				InputStream in = entity.getContent();

				StringBuffer out = new StringBuffer();
				int n = 1;
				while (n>0) {
					byte[] b = new byte[4096];

					n =  in.read(b);

					if (n>0) out.append(new String(b, 0, n));

				}

				return out.toString();

			}

			@Override
			protected String doInBackground(Void... params) {
				String url ="http://next.ws.toyota.com/DISREST/rest/getDealers?timeStamp=1379441483822&brandId=1&resultsMode=full&resultsFormat=json&resultsMax=1&longitude="+this.longitude+"&latitude="+this.latitude;
				HttpClient httpClient = new DefaultHttpClient();
				HttpContext localContext = new BasicHttpContext();
				HttpGet httpGet = new HttpGet(url);
				String text = null;
				try {

					HttpResponse response = httpClient.execute(httpGet, localContext);

					HttpEntity entity = response.getEntity();

					text = getContentFromEntity(entity);
					
				} catch (Exception e) {
					Log.d("Nearby", e.getMessage());
					return e.getLocalizedMessage();
				

				}

				return text;

			}

			@SuppressLint("NewApi")
			@TargetApi(Build.VERSION_CODES.HONEYCOMB)
			protected void onPostExecute(String results) {
				String lineOne = ""; 
				String cityName = "";
				String countryID = "";
				String postcode = "";
				String stateOrProvinceCountrySubDivisionID = "";
				double latitudeDisplay=0.0;
				double longitudeDisplay=0.0;
				String companyNameDisplay = "";

				if (results!=null) {
					try{
						System.out.println(results);
						JSONObject disResponse = (JSONObject)new JSONParser().parse(results);
						Object dealerLocatorDataArea = disResponse.get("showDealerLocatorDataArea");
						Object dealerLocatorDetailArray = ((JSONObject)dealerLocatorDataArea).get("dealerLocator");
						Object dealerLocatorDetailObject = ((JSONArray)dealerLocatorDetailArray).get(0);
						Object dealerLocatorDetailArray2 = ((JSONObject)dealerLocatorDetailObject).get("dealerLocatorDetail");
						Object dealerLocatorDetail = ((JSONArray)dealerLocatorDetailArray2).get(0);
						Object dealerParty = ((JSONObject)dealerLocatorDetail).get("dealerParty");
						Object specifiedOrganization = ((JSONObject)dealerParty).get("specifiedOrganization");
						Object companyName = ((JSONObject)specifiedOrganization).get("companyName");
						Object primaryContactArray = ((JSONObject)specifiedOrganization).get("primaryContact");
						Object primaryContact = ((JSONArray)primaryContactArray).get(0);
						JSONObject postalAddress = (JSONObject) ((JSONObject)primaryContact).get("postalAddress");
						
						Object proxGroup = ((JSONObject)dealerLocatorDetail).get("proximityMeasureGroup");
						Object geoCoor = ((JSONObject)proxGroup).get("geographicalCoordinate");
						Object latObj = ((JSONObject)geoCoor).get("latitudeMeasure"); 
						Object longObj = ((JSONObject)geoCoor).get("longitudeMeasure"); 
						
						latitudeDisplay = (Double) ((JSONObject)latObj).get("value");
						longitudeDisplay = (Double) ((JSONObject)longObj).get("value");
						
						System.out.println("The final dealer l and l: "+latitudeDisplay+" "+longitudeDisplay);

						companyNameDisplay = (String) ((JSONObject)companyName).get("value");
						//lineOne
						lineOne = (String) ((JSONObject)postalAddress.get("lineOne")).get("value");
						//cityName
						cityName = (String) ((JSONObject)postalAddress.get("cityName")).get("value");
						//countryID
						countryID = ((String)postalAddress.get("countryID"));
						//postcode
						postcode = (String) ((JSONObject)postalAddress.get("postcode")).get("value");
//						/stateOrProvinceCountrySubDivisionID
						stateOrProvinceCountrySubDivisionID = (String)((JSONObject)postalAddress.get("stateOrProvinceCountrySubDivisionID")).get("value");
						
						
						
					} catch(Exception e){
						Log.d("Nearby", e.getMessage());
						e.printStackTrace();
					}
//					TextView et = (TextView)findViewById(R.id.show_message);
//					et.setText(lineOne+"\n"+cityName+"\n"+countryID+"\n"+postcode+"\n"+stateOrProvinceCountrySubDivisionID);
					GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
					LatLng dealer = new LatLng(latitudeDisplay, longitudeDisplay);
			        map.moveCamera(CameraUpdateFactory.newLatLngZoom(dealer, 13));

					 map.addMarker(new MarkerOptions()
		                .title(companyNameDisplay)
		                .snippet(lineOne+"\n"+cityName+"\n"+countryID+"\n"+postcode+"\n"+stateOrProvinceCountrySubDivisionID)
		                .position(dealer));


					
				}

				

			}

		}

	
}
